var sysUser = {
    baseUrl: "/lrduser",
    entity: "sysUser",
    tableId: "sysUserTable",
    toolbarId: "toolbar",
    unique: "userId",
    currentItem: {}
};

sysUser.queryParams = function (params) {
	if(!params){
		return {
			userId:$("#userId").val(),
			userName:$("#userName").val(),
			orgCd:$("#orgCd").attr("orgCd"),
			roleCd:$("#roleCd").attr('roleCd')
		}
	}
	var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
    	page: params.offset/params.limit+1, //页码
        limit: params.limit,//页面大小
        userId:$("#userId").val(),
		userName:$("#userName").val(),
		orgCd:$("#orgCd").attr("orgCd"),
		roleCd:$("#roleCd").attr('roleCd')
		};
    return temp;
};

sysUser.responseHandler = function(response){
	if(response.code =='200'){
		return response.data;
	}
	return false;
};
sysUser.select = function (layerTips) {
    var rows = sysUser.table.bootstrapTable('getSelections');
    if (rows.length == 1) {
    	sysUser.currentItem = rows[0];
        return true;
    } else {
        layerTips.msg("请选中一行");
        return false;
    }
};

sysUser.init = function (params) {
    sysUser.table = $('#' + sysUser.tableId).bootstrapTable({
    	url: sysUser.baseUrl+'/user', //请求后台的URL（*）
    	method: 'get', //请求方式（*）
    	queryParams: sysUser.queryParams,//传递参数（*）
        toolbar: '#' + sysUser.toolbarId, //工具按钮用哪个容器
        cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true, //是否显示分页（*）
        sortOrder: sysUser.order, //排序方式
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 10, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        showColumns: false, //是否显示所有的列
        showRefresh: true, //是否显示刷新按钮
        minimumCountColumns: 2, //最少允许的列数
        clickToSelect: true, 
        sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
        showToggle: true, //是否显示详细视图和列表视图的切换按钮
        singleSelect:true,
        uniqueId: sysUser.unique, //每一行的唯一标识，一般为主键列
        responseHandler:sysUser.responseHandler,
        columns:[{
        	checkbox:true
        },{  
            title: '序号',//标题  可不加  
            formatter: function (value, row, index) {  
                return index+1;  
            }  
        },{
            field: 'corpCd',
            title: '法人行号'
        },{
            field: 'corpName',
            title: '法人名称'
        },{
            field: 'userId',
            title: '登录账号'
        },
        /*{
            field: 'managerid',
            title: '员工号'
        },*/{
            field: 'userName',
            title: '姓名'
        },{
            field: 'orgName',
            title: '所属机构'
        },{
            field: 'name',
            title: '用户角色'
        },{
            field: 'jlFlagC',
            title: '状态'
        }]
    });
};
sysUser.refresh = function () {
	sysUser.table.bootstrapTable('refresh', sysUser.queryParams());
};
layui.use(['form', 'layedit', 'laydate'], function () {
    sysUser.init();
    var editIndex;
    var layerTips = layui.layer,
        layer = layui.layer, //获取当前窗口的layer对象
        form = layui.form,
        layedit = layui.layedit,
        laydate = layui.laydate;
    var addBoxIndex = -1;
    //初始化页面上面的按钮事件
    $('#btn_query').on('click', function () {
    	if($("#userName")==''){
    		$("#userName").val('');
    	};
    	if($('#userId')==''){
    		$("#userId").val('');
    	};
    	if($("#orgCd").val()==''){
    		$("#orgCd").removeAttr('orgCd');
    	}
    	if($('#roleCd').val()==''){
    		$("#roleCd").removeAttr("roleCd");
    	};
    	sysUser.table.bootstrapTable('refresh');
    });
    
    $('#btn_clear').on('click',function(){
    	$('#userName').val('');
    	$('#userId').val('');
    	$("#orgCd").val('');
    	$('#roleCd').val('');
    });
    
    $('#btnAdd').on('click',function(){
    	$.get('sysUser/add', null, function (form) {
    		var index = layer.open({
                type: 1,
                title: '添加用户',
                content: form,
                btn: ['保存', '取消'],
                shade: false,
                offset: ['20px', '20%'],
                area: ['500px', '450px'],
                maxmin: true,
                yes: function (index) {
                	layedit.sync(editIndex);
                    //触发表单的提交事件
                    $('form.layui-form').find('button[lay-filter=add]').click();
                },
                full: function (elem) {
                    var win = window.top === window.self ? window : parent.window;
                    $(win).on('resize', function () {
                        var $this = $(this);
                        elem.width($this.width()).height($this.height()).css({
                            top: 0,
                            left: 0
                        });
                        elem.children('div.layui-layer-content').height($this.height() - 95);
                    });
                },
                success: function (layero, index) {
                	var form = layui.form;
                    editIndex = layedit.build('roleCd1');
                    form.render();
                	orgTree2('add');
                   	$('#orgCdQuery1').on('click',function(){
                   		$("#orgCd1").val("");
                   		$("#myModal3").modal({
                   			backdrop:false
                   		});
                	});
                   	$("#roleNameQuery1").on("click",function(){
                   		$("#roleCd").val("");
                   		$("#myModal4").modal({
                   			backdrop:false
                   		});
                   	});
                   	$("#take_back1").on("click",take_back);
                   	
                    
                    form.on('submit(add)', function (data) {            	
                        var corpCd = $('#corpCd1').val();
                    	var userId = $('#userId1').val();
                    	var userName = $('#userName1').val();
                    	var orgCd = $('#orgCd1').attr('orgCd');
                    	var roleCds = $('#roleName1').attr('roleCd').split(',');
                    	var idNo = $("#idNo").val()//身份证号
                    	if(!IdentityCodeValid(idNo)){
                    		layerTips.msg('身份证有误');
                    		return false;
                    	};
                    	var telNo = $("#telNo").val();//手机号
                    	var managerid = $("#managerid").val();//员工号
                    	var data2={'corpCd':corpCd,'userId':userId,'userName':userName,'orgCd':orgCd,'roleCds':roleCds,'idNo':idNo,'telNo':telNo,'managerid':managerid};
                    	$.ajax({
                    		type:"post",
                    		url:sysUser.baseUrl+'/user',
                    		dataType:"json",
                    		contentType:"application/json",
                    		data:JSON.stringify(data2),
                    		success:function(data){
                    			if(data.code=="200"){
                    				$('#orgCd1').removeAttr('orgCd');
                    				$('#roleName1').removeAttr('roleCd'); 
                    				layer.close(index);
                    				layerTips.msg('保存成功');
                    				sysUser.refresh();
                    			}else{
                    				layer.msg(data.message);
                    			}
                    		}
                    	});
                    	return false;
                    });
                }
    		})
    	})
    });
    $('#btnEdit').on('click',function(){
    	if (sysUser.select(layerTips)) { 
        	$.get('sysUser/edit',null,function(form){
        		var index = layer.open({
                    type: 1,
                    title: '修改用户',
                    content: form,
                    btn: ['保存', '取消'],
                    shade: false,
                    offset: ['20px', '30%'],
                    area: ['600px', '400px'],
                    id: 'LAY_layuipro',
                    zIndex:-1,
                    maxmin: false,
                    yes: function (index) {
                        //触发表单的提交事件
                        $('form.layui-form').find('button[lay-filter=add]').click();
                    },
                    success:function(layero, index){
                    	orgTree2('edit');
                       	$('#orgCdQuery1').on('click',function(){
                       		$("#orgCd1").val("");
                       		$("#myModal3").modal({
                       			backdrop:false
                       		});
                    	});
                       	$("#roleNameQuery1").on("click",function(){
                       		$("#roleCd").val("");
                       		$("#myModal4").modal({
                       			backdrop:false
                       		});
                       	});
                       	$("#take_back1").on("click",take_back);
                    	var form = layui.form;
                        $('#corpCd1').val(sysUser.currentItem.corpCd);
                		$('#userId1').val(sysUser.currentItem.userId);
                		$('#userName1').val(sysUser.currentItem.userName);
                		$('#orgCd1').val(sysUser.currentItem.orgName).attr('orgCd',sysUser.currentItem.orgCd);
                		$('#roleName1').val(sysUser.currentItem.name).attr('roleCd',sysUser.currentItem.roleCds);
                		$('#jlFlag').val(sysUser.currentItem.jlFlag);
                		$("#idNo").val(sysUser.currentItem.idNo)//身份证号
                    	$("#telNo").val(sysUser.currentItem.telNo);//手机号
                    	$("#managerid").val(sysUser.currentItem.managerid);//员工号
                        form.render();
                		$(".layui-form-item").removeAttr('hidden');
                		form.on('submit(add)', function (data) {
                    		var corpCd = $('#corpCd1').val();
                    		var userId= $('#userId1').val();
                    		var userName = $('#userName1').val();
                    		var idNo = $("#idNo").val()//身份证号
                        	var telNo = $("#telNo").val();//手机号
                        	var managerid = $("#managerid").val();//员工号
                    		var orgCd = $('#orgCd1').attr('orgCd');
                    		var roleCds = $('#roleName1').attr('roleCd').split(',');
                    		var jlFlag =$('#jlFlag').val();
                			var data0={'corpCd':corpCd,'userId':userId,'userName':userName,'orgCd':orgCd,'roleCds':roleCds,'jlFlag':jlFlag,
                					"telNo":telNo,"idNo":idNo
                			};
                			$.ajax({
                				type:'put',
                				dataType:"json",
                        		contentType:"application/json",
                				url:sysUser.baseUrl+'/user',
                				data:JSON.stringify(data0),
                				success:function(data){
                					if(data.code=='200'){
                						layerTips.msg("修改成功！");
                						layer.close(index);
                						sysUser.refresh();
                					}else{
                						layerTips.msg(data.message);
                					}
                				},
                			});
                			return false;
                		})
                    }
        		})
        	})
    	}
    });
    $('#btnDel').on('click',function(){
    	if (sysUser.select(layerTips)) {    		
    		var userId = sysUser.currentItem.userId;
    		layer.confirm('确定删除数据吗？', null, function (index) {
    			$.ajax({
        			type:'delete',
        			dataType:"json",
            		contentType:"application/json",
        			url:sysUser.baseUrl+'/user/'+userId,
        			success:function(data){
        				if(data.code=='200'){
        					layerTips.msg("移除成功！");
        					sysUser.refresh();
        				}else{
        					layerTips.msg(data.message);
        				}
        			},
        		});
    		});
    	}
    });
    $('#btnReset').on('click',function(){
    	if (sysUser.select(layerTips)) {    		
    		var userId = sysUser.currentItem.userId;
    		var data0={"userId":userId};
    		layer.alert('确定重置密码？',null,function(index){
    			$.ajax({
    				type:'post',
    				dataType:"json",
    				contentType:"application/json",
    				url:sysUser.baseUrl+'/resetPwd',
    				data:JSON.stringify(data0),
    				success:function(data){
    					if(data.code=='200'){
    						layerTips.msg("重置成功")    						
    					}else{
    						layerTips.msg(data.message);    						
    					}
    				},
    			});
    			layer.close(index);
    		});
    	}
    });
});

$("#orgCdQuery").on("click",function(){
	$("#orgCd").val("");
	$("#myModal1").modal({
		backdrop:false
	});
	orgTree();
});
function orgTree(){
	var setting = {
			data: {
				simpleData: {
					enable: true,
				},
			},
			callback: {
				beforeClick: function(treeId, treeNode) {
					$("#orgCd").val(treeNode.name).attr("orgCd",treeNode.id);
					$("#myModal1").modal("hide");
					return true;
				}
			}
		};
	$.ajax({
		type:"get",
		url: sysUser.baseUrl+'/user/orgTree',
		dataType:"json",
		contentType:"application/json",
		success:function(response){
			if(response.code=="200"){
				var org=response.data;
				$.fn.zTree.init($("#tree1"), setting,org);
			}
		},error:function(data){
			layer.alert('查询失败');
		}
	});
}


$("#roleCdQuery").on("click",function(){
	$("#roleCd").val("");
	$("#myModal2").modal({
		backdrop:false
	});
	roleTree();
});
function roleTree(){
	$.ajax({
		type:'get',
		dataType:'json',
    	contentType	:'application/json',
		url:sysUser.baseUrl+"/user/roleList",
		success:function(data){
			if(data.code=='200'){
				var html="";
				for(var i=0;i<data.data.length;i++){
					var result = data.data[i];
					html+='<tr roleCd="'+result.roleCd+'"roleName="'+result.roleName+'">';
					html+='<td><input type="checkbox" name="checkBox" roleCd="'+result.roleCd+'"roleName="'+result.roleName+'"/></td>';
					html+='<td class="text-center">' + (i+1)+ '</td>';						
					html+='<td>' + result.roleCd + '</td>';						
					html+='<td>' + result.roleName + '</td>';
					html+='<td>' + result.desc + '</td>';
					html+='</tr>';
				}
				$("#tree2").html(html);
			}
		},
		error:function(){
			layer.alert('查询失败');
		}
	})
	
}
//选择带回
$("#take_back").on("click",function(){
	var checkboxs=$("[name=checkBox]:checked");
	var roleStr="",roleNameStr="";
	if(checkboxs.size()>0){
		if(checkboxs.size()==1){
			roleStr="'"+checkboxs.attr("roleCd")+"'";
			roleNameStr=checkboxs.attr("roleName");
			}else{
				for(var i=0;i<checkboxs.size();i++){
					if(i==checkboxs.size()-1){
						roleStr+= "'"+checkboxs.eq(i).attr("roleCd")+"'";
						roleNameStr+=checkboxs.eq(i).attr("roleName");
					}else{
						roleStr+="'"+checkboxs.eq(i).attr("roleCd")+"',";
						roleNameStr+=checkboxs.eq(i).attr("roleName")+",";
					}
				}
			}
	$("#roleCd").val(roleNameStr).attr("roleCd",roleStr);
	$("#myModal2").modal("hide");
	}
});

var setting = {
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {
				$("#orgName").val(treeNode.name).attr('orgCd',treeNode.id);
				$("#myModal1").modal("hide").on("hidden.bs.modal");
				return true;
			}
		}
	};
function orgTree2(type){
	$.ajax({
		type:"get",
		url:sysUser.baseUrl+"/user/queryInsert",
		dataType:"json",
		success:function(response){
			if(response.code=="200"){
				var org=response.data.org;
				var role=response.data.role;
				var corpCd=response.data.corpCd;
				if(type=='add') {
                    $('#corpCd1').val(corpCd);
                    if (corpCd != '1') {
                        $('#corpCd1').attr("readOnly", true);
                    }
                }
				$.fn.zTree.init($("#orgTree2"), setting, org);
				var html="";
				for(var i=0;i<role.length;i++){
					var result = role[i];
					html+='<tr>';
					html+='<td><input type="checkbox" name="checkBox" roleCd="'+result.roleCd+'" roleName="'+result.roleName+'"/></td>';
					html+='<td class="text-center">' + (i+1)+ '</td>';						
					html+='<td>' + result.roleCd + '</td>';						
					html+='<td>' + result.roleName + '</td>';
					html+='<td>' + result.desc + '</td>';
					html+='</tr>';
				}
				$("#roleTree2").html(html);
			}
		},error:function(data){
			layer.alert('查询失败');
		}
	});
	var setting = {
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				beforeClick: function(treeId, treeNode) {
					$("#orgCd1").val(treeNode.name).attr('orgCd',treeNode.id);
					$("#myModal3").modal("hide").on("hidden.bs.modal");;
					return true;
				}
			}
		};
}
function take_back(){
	var checkboxs=$("[name=checkBox]:checked");
	var roleStr="",roleNameStr="";
	if(checkboxs.size()>0){
		if(checkboxs.size()==1){
			roleStr=checkboxs.attr("roleCd");
			roleNameStr=checkboxs.attr("roleName");
			}else{
				for(var i=0;i<checkboxs.size();i++){
					if(i==checkboxs.size()-1){
						roleStr+=checkboxs.eq(i).attr("roleCd");
						roleNameStr+=checkboxs.eq(i).attr("roleName");
					}else{
						roleStr+=checkboxs.eq(i).attr("roleCd")+",";
						roleNameStr+=checkboxs.eq(i).attr("roleName")+",";
					}
				}
			}
		$("#roleName1").val(roleNameStr).attr("roleCd",roleStr);
		$("#myModal4").modal("hide");
	}
}
//身份证校验
function IdentityCodeValid(code) { 
    var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
    var tip = "";
    var pass= true;
    ///^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
    if(!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)){
        tip = "身份证号格式错误";
        pass = false;
    }
    
   else if(!city[code.substr(0,2)]){
        tip = "地址编码错误";
        pass = false;
    }
    else{
        //18位身份证需要验证最后一位校验位
        if(code.length == 18){
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
            //校验位
            var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
            var sum = 0;
            var ai = 0;
            var wi = 0;
            for (var i = 0; i < 17; i++)
            {
                ai = code[i];
                wi = factor[i];
                sum += ai * wi;
            }
            var last = parity[sum % 11];
            if(parity[sum % 11] != code[17]){
                tip = "校验位错误";
                pass =false;
            }
        }
    }
    if(!pass);
    return pass;
}
